<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/22
 * Time: 16:14
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\api\model\user\Users;
use app\common\model\Agency;
use app\common\model\AgencySalesman;
use think\Db;
use think\Exception;

class Agencies extends AdminController
{

    public function list() {
        $form = $this->getAndCheckForm([
            ['page', 'require|integer',],
            ['rows', 'require|integer',],
        ]);

        $query = Db::table('agency a');

        $keywords = $form['keywords'] ?? null;
        if ($keywords) {
            $query->where('a.name', 'like', "%$keywords%");
        }

        $result = $query->order('a.id','desc')
            ->paginate($form['rows']??10, $form['page']??1)
            ->toArray();
        foreach ($result['data'] as & $item) {
            $salesman =
            Db::table('agency_salesman s')
                ->join('users u','u.id=s.userid')
                ->where('s.agency_id','=',$item['id'])
                ->where('s.agency_role=1')
                ->field('u.mobile')
                ->find();
            if ($salesman) {
                $item['admin_username'] = $salesman['mobile'];
            }

            $item['contract_expired'] = date('Y-m-d', $item['contract_expired']);
        }
        $result['code'] = 200;

        return $result;
    }

    public function save() {
        $valid = [
            ['name', 'require', '名称不能为空'],
            ['contract_expired', 'date',],
            ['admin_mobile', '^[A-Za-z][A-Za-z1-9_-]{6,20}$', '用户名必须是6-20位、字母或字母开头加数字'],
        ];
        $form = $this->getAndCheckForm($valid);

        if (isset($form['contract_expired'])) $form['contract_expired'] = strtotime($form['contract_expired']);

        try{
            Db::startTrans();

            if (isset($form['id'])) {
                $agency = Agency::update($form,[],Agency::getSaveFields());
            } else {
                $agency = Agency::create($form,Agency::getSaveFields());
            }

            $adminUsername = $form['admin_username'] ?? null;
            if ($adminUsername) {
                $salesman = AgencySalesman::get(['agency_id' => $agency->id, 'agency_role' => 1]);
                if (empty($salesman)) {
                    $user = Users::get(['mobile' => $adminUsername]);
                    if (empty($user)) {
                        $user = Users::create([
                            'mobile' => $adminUsername,
                            'regtime' => time(),
                            'password' => passEncrypt($form['admin_password'] ?? mt_rand(1,999999)),
                        ]);
                    }
                    $salesman = new AgencySalesman();
                    $salesman->agency_id = $agency->id;
                    $salesman->userid = $user->id;
                    $salesman->agency_role = 1;
                    $salesman->code = AgencySalesman::generateCode();
                    $salesman->save();
                }
            }

            Db::commit();
            return ApiResponse::success();
        }catch (\Exception $ex){
            Db::rollback();
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,$ex->getMessage());
        }

    }

    public function del() {
        $id = intval(input('post.id'));
        if ($id < 0) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID);
        elseif (0 == $id) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'默认机构，无法删除');

        Agency::destroy($id);

        return ApiResponse::success();
    }

    public function check_account() {
        $form = $this->getAndCheckForm([
            ['mobile', 'require',],
        ]);

        $mobile = $form['mobile'];
        $re = Db::query('select 1 from users where mobile=:mobile limit 1', ['mobile'=>$mobile]);
        $re = $re[0]??null;
        return ApiResponse::success(['exists' => (!empty($re))]);
    }

}